﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Services;
using IntelligentAgriculture.WebAPI.Application.Command.DepartMentCommand;
using IntelligentAgriculture.WebAPI.Application.Command.VendorModelCommand;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;

namespace IntelligentAgriculture.WebAPI.Application.CommandHandler.DepartMentCommandHandler
{
    public class DepartMentExportCommandHandler : IRequestHandler<DepartMentExportCommand, IActionResult>
    {

        private readonly IDepartMentService departService;
        private readonly IMapper imapper;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="vendorModelService"></param>
        public DepartMentExportCommandHandler(IDepartMentService departService, IMapper imapper)
        {
                this.departService = departService;
                this.imapper = imapper;
        }

        /// <summary>
        /// 部门导出
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public  async Task<IActionResult> Handle(DepartMentExportCommand request, CancellationToken cancellationToken)
        {

            var list = await departService.DepartMnetList(request.InPut);
            //获取数据
            var data = list.Data;

            //转换为导出类型
            var exportCustomerDto = imapper.Map<List<DepartMentOutPut>, List<DepartMentExportOutPut>>(data);

            // 创建一个内存流对象
            MemoryStream ms = new MemoryStream();

            // 异步将导出的客户数据保存到内存流中
            await ms.SaveAsAsync(exportCustomerDto);

            // 将内存流的读取位置重置到开始位置
            ms.Seek(0, SeekOrigin.Begin);

            // 返回一个文件流结果，指定内容类型和文件下载名
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "部门信息.xlsx"
            };

        }






    }





}
